package com.gzx.plugin.data.wckj.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.gzx.plugin.data.wckj.api.ApiFactory;
import com.gzx.plugin.data.wckj.api.ApiResponse;
import com.gzx.plugin.data.wckj.config.WckjConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@DS("data")
@RequiredArgsConstructor
public class CaseInfoThreadPoolService {

    private final WckjConfig wckjConfig;

    private final CaseInfoBatchSaveService caseInfoBatchSaveService;

    public void runCaseService(List<String> ywyhidList, String orgCode, String orgPwd, String projectCode) {
        if (CollectionUtils.isEmpty(ywyhidList)) {
            log.warn("任务列表为空，拒绝提交");
            return;
        }

        CountDownLatch latch = new CountDownLatch(ywyhidList.size());//对方接口限制每秒5个并发；
        ConcurrentHashMap<String, ApiResponse> resultMap = new ConcurrentHashMap<>();

        // 创建信号量，限制每秒最多 5 个请求
        Semaphore semaphore = new Semaphore(5);

        for (String partnerUserId : ywyhidList) {
            Thread.startVirtualThread(() -> {
                try {
                    // 获取许可，限制每秒请求数
                    semaphore.acquire();
                    ApiResponse apiResponse = ApiFactory.callRemoteApi(partnerUserId, wckjConfig.getUrl(), wckjConfig.getGetCaseInfo(), orgCode, orgPwd);
                    if (apiResponse != null) {//接口超频、接口查询不到等等一系列异常情况都不能放入用户id到下面的map中，等待下一次定时任务处理即可
                        resultMap.put(partnerUserId, apiResponse); // 使用线程安全的 ConcurrentHashMap
                    }
                } catch (Exception e) {
                    log.error("请根据这条异常打印的信息，分析是否是每秒限流5次请求出现异常...", e);
                } finally {
                    latch.countDown(); // 减少计数器
                    semaphore.release();// 在每次请求后释放许可
                }
            });
        }

        try {
            boolean completed = latch.await(5, TimeUnit.SECONDS); // 等待所有线程完成,超时时间不能设置太短，对方接口响应有大于3秒的情况
            if (completed && !resultMap.isEmpty()) {
                caseInfoBatchSaveService.saveBatchRequestData(projectCode, resultMap);
            } else if (resultMap.isEmpty()) {
                log.info("5个并发线程的接口请求均未返回数据，请确认是否接口请求频率超限....");
            } else {
                log.info("CountDownLatch有超时的情况，本次不处理...");
            }
        } catch (Exception e) {
            Thread.currentThread().interrupt();
            log.error("接口超时或出现多线程异常...", e);
        }
    }
}
